package com.zmm.study.order.controller;

import com.zmm.common.base.model.Result;
import com.zmm.common.base.model.ResultCode;
import com.zmm.common.exception.handle.BusinessException;
import com.zmm.study.order.model.Order;
import com.zmm.study.order.service.OrderService;
import com.zmm.util.verify.BindingResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @Description:
 * @Name OrderController
 * @Author Zebulon
 * @Date By 2021-07-21 23:19:15
 */
@Controller
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 去到这个 订单新增页面
     * @description:
     * @author: Zebulon
     * @date: 2021-07-21 23:25:08

     * @return: java.lang.String
     **/
    @RequestMapping(value = "/to/add/",method = RequestMethod.GET)
    public String toAddOrder(){
        return "order_add";
    }


    /**
     * 新增订单 - 控制层
     * @description:
     * @author: Zebulon
     * @date: 2021-07-21 23:25:21
     * @param order:
     * @param result:
     * @return: com.zmm.common.base.model.Result
     **/
    @ResponseBody
    @RequestMapping(value = "/do/add",method = RequestMethod.POST)
    public Result addOrder(Order order, BindingResult result){

        // 1.表达校验
        if (result.hasErrors()){
            //  Model model
            //model.addAttribute("orders",result)
            return BindingResultUtil.paramVerify(result);
        }

        try {
            boolean flag = orderService.addOrder(order);
            if (!flag){
                // 新增失败
                return Result.error(ResultCode.INSERT_FAILED);
            }
        } catch (BusinessException e) {
            log.error("SAVE-ORDER-[addOrder]  end: e-{}", e);
            return Result.error(e.getCode().getCode(),e.getMessage());
        } catch (Exception e){
            log.error("SAVE-ORDER  end: e-{}", e);
        }
        return Result.ok();
    }
}
